<?php

// 服务器文件处理
//
//
class Files {

	var $website;

	function __construct(&$website) {
		$this->website = $website;
	}

	// 保存上传地址
	// args:{
	//  mode    上传的文件及文件夹权限 0664
	//  path    存放地址   默认 $this->website['path']['upload']['image'].$tm
	//  image   默认true       是否上传的是图片
	//  time    默认 'y/m/d'   false不加地址，直接使用path地址
	//  sfx     默认 website['safe']['upload']['sfx']
	//  name    上传字段名称 必须
	// }
	function upload($args = []) {

		// print_r($_FILES[$args['name']]);exit();
		$sfxs = $args['sfx'] ?? $this->website['safe']['upload']['sfx'];
		$mod = $args['mod'] ?? 0664;
		// 是否检测是图片 默认检测
		$isImg = $args['image'] ?? true;
		// 是否检测后缀  默认检测
		$isSfx = $args['sfx'] ?? true;
		$tm = date('/Y/m/d');
		$path = $args['path'] ?? $this->website['path']['upload']['image'] . $tm;
		$upFiles = $this->upFiles($args['name']);

		$newPaths = [];
		foreach ($upFiles as $k => $v) {
			$sfx = pathinfo($v['name'])['extension'];
			$newPath = $path . '/' . md5_file($v['tmp_name']) . ($sfx ? ('.' . $sfx) : '');

			if ($isSfx === false && !in_array($sfx, $sfxs)) {
				$newPaths[] = $v['name'] . '文件格式不正确,可上传文件后缀：' . explode(array_values($upFiles));
				continue;
			} elseif ($isImg === true && !count(getimagesize($v['tmp_name']))) {
				$newPaths[] = $v['name'] . '上传文件只能是图片文件';
				continue;
			} elseif ($this->createDir($newPath) !== true) {
				$newPaths[] = $newPath . '文件夹创建错误,请检查权限';
				continue;
			} elseif ($v['error'] === UPLOAD_ERR_OK) {
				if (move_uploaded_file($v['tmp_name'], $newPath)) {
					$newPaths[] = $newPath;
					chmod($newPath, $mod);
				} else {
					$newPaths[] = $v['name'] . '上传移动失败!';
				}
			} else {
				switch ($v['error']) {
				case 1: // UPLOAD_ERR_INI_SIZE
					$newPaths[] = $v['name'] . "-超过配置文件中上传文件的大小";
					break;
				case 2: // UPLOAD_ERR_FORM_SIZE
					$newPaths[] = $v['name'] . "-超过表单中配置文件的大小";
					break;
				case 3: // UPLOAD_ERR_PARTIAL
					$newPaths[] = $v['name'] . "-文件被部分上传";
					break;
				case 4: // UPLOAD_ERR_NO_FILE
					$newPaths[] = $v['name'] . "-没有文件被上传";
					break;
				case 6: // UPLOAD_ERR_NO_TMP_DIR
					$newPaths[] = $v['name'] . "-没有找到临事文件目录";
					break;
				case 7: // UPLOAD_ERR_CANT_WRITE
					$newPaths[] = $v['name'] . "-文件不可写";
					break;
				case 8: // UPLOAD_ERR_EXTENSION
					$newPaths[] = $v['name'] . "-php扩展程序中断了上传程序";
					break;
				}
			}
		}
		return count($newPaths) == 1 ? $newPaths[0] : $newPaths;
	}

	// 整合上传文件
	function upFiles($name) {
		$files = $_FILES[$name];


		if (is_string($files['name'])) {
			return [$files];
		} else {
			$info = [];

			foreach ($files['name'] as $k => $v) {
//2维数组转换成1维数组
				//取出一维数组的值，然后形成另一个数组
				//新的数组的结构为：info=>i=>('name','size'.....)
				$info[$k]['name'] = $files['name'][$k];
				$info[$k]['size'] = $files['size'][$k];
				$info[$k]['type'] = $files['type'][$k];
				$info[$k]['tmp_name'] = $files['tmp_name'][$k];
				$info[$k]['error'] = $files['error'][$k];
			}
			return $info;
		}
	}

	//功能：逐层创建文件夹
	function createDir($path, $mode = 0755, $recursive = false) {
		$path = dirname($path);
		$path = str_replace($this->website['path']['data'], '', $path);
		$arr = explode('/', $path);
		array_shift($arr);
		$paths = $this->website['path']['data'];
		foreach ($arr as $v) {
			$paths .= '/' . $v;
			if (!is_dir($paths)) {
				try {
					if (!mkdir($paths, $mode, $recursive)) {
						return '创建文件夹：' . $paths . '失败!';
					}
				} catch (Exception $e) {
					return $e->getMessage();
				}
			}
		}
		return true;
	}

}